<?php

function option_load()
{
	global $options , $option;
	foreach($options as $value) {
		$option[($value['id'])] = get_option('iGoogler_'.$value['id'], $value['std']);
	}
}


function seo_title($sep) {
		/*
	 * Print the <title> tag based on what is being viewed.
	 */
	global $page, $paged;

	wp_title( $sep, true, 'right' );

	// Add the blog name.
	bloginfo( 'name' );

	// Add the blog description for the home/front page.
	$site_description = get_bloginfo( 'description', 'display' );
	if ( $site_description && ( is_home() || is_front_page() ) )
		echo " | $site_description";

	// Add a page number if necessary:
	if ( $paged >= 2 || $page >= 2 )
		echo ' | ' . '第' . max( $paged, $page ) . '页';
}

function time_since($older_date, $newer_date = false)
{
	$chunks = array(
	//    array(60 * 60 * 24 * 365 , '年'),
	//   array(60 * 60 * 24 * 30 , '月'),
	array(60 * 60 * 24 * 7, 'week'),
	array(60 * 60 * 24 , 'day'),
	array(60 * 60 , 'hour'),
	array(60 , 'minute'),
	);
	$newer_date = ($newer_date == false) ? (time()+(60*60*get_settings("gmt_offset"))) : $newer_date;
	$since = $newer_date - $older_date;
	if($since < 604800)
	{
		//显示时间的前半部分
		for ($i = 0, $j = count($chunks); $i < $j; $i++)
		{
			$seconds = $chunks[$i][0];
			$name = $chunks[$i][1];
			if (($count = floor($since / $seconds)) != 0)
			{
				break;
			}
		}
		$output = "$count {$name}";
		if($count>1)
		$output .= 's';
		return $output." ago";
		//在24小时以外的时间显示格式
	}else{
		the_time('Y-m-j');
	}
}


function type_description (){
	if(is_category() || is_tag() || is_author() || is_date() || is_search() ) {
		echo '<div class="path">';
	
		if( is_category() ) echo '分类描述：'.category_description();
		elseif ( is_tag() ) echo '标签描述：'.tag_description();
		elseif ( is_author() ) echo '作者简介：'.author_description();
		elseif ( is_search() ) echo '您搜索的是：'.$_GET['s'];
		elseif ( is_date() ) echo wp_title('').' 的存档';
		echo '</div>';
	}	
}

function category_path ($show_last = true, $category_ID = 0, $diplay_link = true, $seperator = ' &raquo; ', $nice_name = false ) {
	if($category_ID == 0 ) {
		$category = get_the_category();
		$category_ID = $category[0]->cat_ID;
	}
	if( !$show_last) {
		$category = get_the_category();
		$category_ID = $category[0]->category_parent;
	}
	if( $category_ID != 0 ) {
		echo get_category_parents($category_ID, true, $seperator);
	}
}

function search_words (){
	$search_engine = array ('google.com'=>'q','baidu.com'=>'wd','bing.com'=>'q','yahoo.com'=>'p','sogou.com'=>'query','soso.com'=>'w');
	if(is_search()&&$_GET['s']!='')
	return $_GET['s'];
	else {
		foreach($search_engine as $key=>$value)
		if(strpos($_SERVER['HTTP_REFERER'],$key))
		{
			$pos1 = strpos($_SERVER['HTTP_REFERER'],'&'.$value.'=');
			$pos2 = strpos($_SERVER['HTTP_REFERER'],'&',$pos1+1);
			if($pos2!=0)
			$str = substr($_SERVER['HTTP_REFERER'],$pos1+3,$pos2-$pos1-3);
			else
			$str = substr($_SERVER['HTTP_REFERER'],$pos1+3);
			$encode1 = mb_detect_encoding($str, array('ASCII','CP936','gb2312','UTF-8'));
			if($encode1 != "CP936")
			{
				$str = urldecode($str);
				$encode2 = mb_detect_encoding($str, array('ASCII','gb2312','GBK','UTF-8'));
				if($encode2 == "EUC-CN")
				$str = mb_convert_encoding($str,'utf-8','gb2312');
			}
			return $str;
		}
		return false;
	}
}

/* Mini Pagenavi v1.0 by Willin Kan. Edit by zwwooooo */
if ( !function_exists('pagenavi') ) {
	function pagenavi( $p = 5 ) { // 取当前页前后各 2 页
		if ( is_singular() ) return; // 文章与插页不用
		global $wp_query, $paged;
		$max_page = $wp_query->max_num_pages;
		if ( $max_page == 1 ) return; // 只有一页不用
		if ( empty( $paged ) ) $paged = 1;
		if ( $paged > 1 ) p_link( $paged - 1, '上一页', '上一页', 'page-nav-pre link' );/* 如果当前页大于1就显示上一页链接 */
		else echo '<span class="page-nav-pre">&nbsp;</span>';
		if ( $paged > $p + 1 ) p_link( 1, '最前页' );
		if ( $paged > $p + 2 ) echo '... ';
		for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { // 中间页
			if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span>" : p_link( $i );
		}
		if ( $paged < $max_page - $p - 1 ) echo '... ';
		if ( $paged < $max_page - $p ) p_link( $max_page, '最后页' );
		if ( $paged < $max_page ) p_link( $paged + 1,'下一页', '下一页', 'page-nav-after' );/* 如果当前页不是最后一页显示下一页链接 */
		else echo '<span class="page-nav-after">&nbsp;</span>';
	}
	function p_link( $i, $title = '', $linktype = '', $class = 'page-numbers' ) {
		if ( $title == '' ) $title = "第 {$i} 页";
		if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
		echo '<a class="'.$class.'" href="', esc_html( get_pagenum_link( $i ) ), '" title="'.$title.'">'.$linktext.'</a>';
	}
}
// -- END ----------------------------------------

function show_query_num() {
	global $wp_query;
	$request = $wp_query->request;
	$posts_per_page = intval(get_query_var('posts_per_page'));
	$paged = intval(get_query_var('paged'));
	$numposts = $wp_query->found_posts;
	$max_page = $wp_query->max_num_pages;
	if(empty($paged) || $paged == 0) {
		$paged = 1;
	}
	if(is_404())
	$current_num = 0;
	else
	$current_num = (($paged-1)*$posts_per_page)+1;
	$str = '获得约<strong>'.$numposts.'</strong>条结果';
	if($paged>1)
	$str.= '，当前是第'.$paged.'页';
	if( is_singular() )
	echo '获得约<strong>1</strong>条结果，用时'.timer_stop(0).'秒';
	else
	echo $str.='，用时'.timer_stop(0).'秒';;
}

function wp_get_related_posts($number = 5,$limit = 5) {
	global $wpdb, $post;
	$temp_post = $post;
	if ( $exclude != '' ) {
		$q = 'SELECT tt.term_id FROM '. $wpdb->term_taxonomy.'  tt, ' . $wpdb->term_relationships.' tr WHERE tt.taxonomy = \'category\' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = '.$post->ID;

		$cats = $wpdb->get_results($q);

		foreach(($cats) as $cat) {
			if (in_array($cat->term_id, $exclude) != false){
				return;
			}
		}
	}

	if(!$post->ID){return;}
	$now = current_time('mysql', 1);
	$tags = wp_get_post_tags($post->ID);

	$taglist = "'" . $tags[0]->term_id. "'";

	$tagcount = count($tags);
	if ($tagcount > 1) {
		for ($i = 1; $i < $tagcount; $i++) {
			$taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
		}
	}

	if ($limit) {
		$limitclause = "LIMIT $limit";
	}	else {
		$limitclause = "LIMIT 5";
	}

	$q = "SELECT p.ID, p.post_title, p.post_content,p.post_excerpt, p.post_date,  p.comment_count, count(t_r.object_id) as cnt FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy ='post_tag' AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id  = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < '$now' GROUP BY t_r.object_id ORDER BY cnt DESC, p.post_date_gmt DESC $limitclause;";

	$related_posts = $wpdb->get_results($q);

	$output = "";

	foreach ($related_posts as $related_post ){
		$output .= '<li>';
		$output .=  '<a href="'.get_permalink($related_post->ID).'" title="相关日志： '.wptexturize($related_post->post_title).'">'.wptexturize($related_post->post_title).'</a>';
		$output .=  '</li>';
	}
	if(empty($related_posts)) $output .= '<li></li>';
	$post = $temp_post;
	return $output;
}

function get_most_comments_posts($number = 5)
{
	global $wpdb,$post;
	$query = $wpdb->get_results('SELECT `ID` , `comment_count`
FROM  `wp_posts` 
WHERE `post_type` = "post" AND `post_status` = "publish"
ORDER BY  `comment_count` DESC 
LIMIT 0 , '.$number,'ARRAY_A');
	$temp_post = $post;
	foreach($query as $value):
	$fpost=get_post(intval($value['ID']));
	setup_postdata($fpost);
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> - '.$value[comment_count].'条评论</li>';
	endforeach;
	$post= $temp_post;
	return $output;
}

function get_random_posts($number = 5)
{
	global $post;
	$temp_post = $post;
	$output = '';
	$rand_posts = get_posts('numberposts='.$number.'&orderby=rand');
	foreach( $rand_posts as $fpost ) :
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> </li>';
	endforeach;
	$post = $temp_post;
	return $output;
}

function get_latest_posts($number = 5)
{
	global $post;
	$temp_post = $post;
	$output = '';
	$rand_posts = get_posts('numberposts='.$number.'&orderby=ID&order=DESC');
	foreach( $rand_posts as $fpost ) :
	$output.='<li><a href="'.get_permalink($fpost->ID).'" title="'.get_the_title($fpost->ID).'">'.get_the_title($fpost->ID).'</a> </li>';
	endforeach;
	$post = $temp_post;
	return $output;
}

/********************************************/
/* $Id: wp-utf8-excerpt.php 23 2010-01-01 14:23:11Z Betty $ */

/* if the host doesn't support the mb_ functions, we have to define them. From Yskin's wp-CJK-excerpt, thanks to Yskin. */
if ( !function_exists('mb_strlen') ) {
	function mb_strlen ($text, $encode) {
		if ($encode=='UTF-8') {
			return preg_match_all('%(?:
					  [\x09\x0A\x0D\x20-\x7E]           # ASCII
					| [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
					|  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
					|  \xED[\x80-\x9F][\x80-\xBF]       # excluding surrogates
					|  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
					| [\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
					|  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
					)%xs',$text,$out);
		}else{
			return strlen($text);
		}
	}
}

/* from Internet, author unknown */
if (!function_exists('mb_substr')) {
    function mb_substr($str, $start, $len = '', $encoding="UTF-8"){
        $limit = strlen($str);
 
        for ($s = 0; $start > 0;--$start) {// found the real start
            if ($s >= $limit)
                break;
 
            if ($str[$s] <= "\x7F")
                ++$s;
            else {
                ++$s; // skip length
 
                while ($str[$s] >= "\x80" && $str[$s] <= "\xBF")
                    ++$s;
            }
        }
 
        if ($len == '')
            return substr($str, $s);
        else
            for ($e = $s; $len > 0; --$len) {//found the real end
                if ($e >= $limit)
                    break;
 
                if ($str[$e] <= "\x7F")
                    ++$e;
                else {
                    ++$e;//skip length
 
                    while ($str[$e] >= "\x80" && $str[$e] <= "\xBF" && $e < $limit)
                        ++$e;
                }
            }
 
        return substr($str, $s, $e - $s);
    }
}

/* the real excerpt function */
if (!function_exists('utf8_excerpt')) {
	function utf8_excerpt ($text) {
		global $post, $option;
	
		if ( '' == $text ) {
			$home_excerpt_length = get_option('iGoogler_excerpt_length');
			$archive_excerpt_length = get_option('iGoogler_excerpt_length');
//set default options
			if ('' == $allowd_tag) {$allowd_tag = '<span><strong>';}	
			if ('' == $home_excerpt_length) {$home_excerpt_length = 200;}
			if ('' == $archive_excerpt_length) {$archive_excerpt_length = 150;}		
			if ('' == $read_more_link) {$read_more_link = '…';}		

			if (is_home()) {
				$length = $home_excerpt_length;
			} else {
				$length = $archive_excerpt_length;
			}			

//get and trim the text
			$text = $post->post_content;
			$text = apply_filters('the_content', $text);
			$text = str_replace(']]>', ']]&gt;', $text);
			$text = trim($text);
			
//			check if the post is already short
			if($length > mb_strlen($text = strip_tags($text, $allowd_tag), 'utf-8')) {
				return force_balance_tags($text);
			}
				
//          check if there is a <!--more--> tag
            $more_position = stripos ($text, "<!--more-->");
            if ($more_position !== false) {
                $text = substr ($text, 0, $more_position);
            } 
            else {

// strip tags now, otherwise the <!--more--> tag is also stripped
				$text = strip_tags($text, $allowd_tag); 		
				$text = trim($text);
            	
//		 		check if the character is worth counting (ie. not part of an HTML tag). From Bas van Doren's Advanced Excerpt, thanks to Bas van Doren.
				$num = 0;
				$in_tag = false;
				for ($i=0; $num<$length || $in_tag; $i++) {
					if(mb_substr($text, $i, 1) == '<')
						$in_tag = true;
					elseif(mb_substr($text, $i, 1) == '>')
						$in_tag = false;
					elseif(!$in_tag)
						$num++;
				}
				$text = mb_substr ($text,0,$i, 'utf-8');            
            }
           
		}

				$text .= " ...";
				$text = force_balance_tags($text);
		
// 		add a "read more" link. If you don't want it, just comment the following line out.
		return $text;
	}
}

function first_p_excerpt()
{
	global $post;
	
	if(preg_match('/<p>(.*)<\/p>/iU',trim(strip_tags($post->post_content,"<p>")),$matches)){
		return $matches[1];
	} else {
		$post_content = explode("\n",trim(strip_tags($post->post_content)));
	return $post_content ['0'];
	}
}

if(get_option('iGoogler_excerpt_first_p'))
	add_filter('get_the_excerpt', 'first_p_excerpt', 9);
else
	add_filter('get_the_excerpt', 'utf8_excerpt', 9);
/********************************************/

?>